from django.shortcuts import render

# Create your views here.
from django.utils.decorators import method_decorator
from django_redis import get_redis_connection
from rest_framework import mixins
from rest_framework import request
from rest_framework import status
from rest_framework.decorators import action
from rest_framework.generics import CreateAPIView, RetrieveAPIView, UpdateAPIView
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.viewsets import GenericViewSet
from rest_framework_jwt.views import ObtainJSONWebToken

from carts.utils import merge_cookie_redis
from goods.models import SKU
from users.models import User
from users.serializer import CreateUserSerializer, UserDetailSerializer, EmailSerializer, UserAddressSerializer, \
    AddressTitleSerializer, AddUserBrowsingHistorySerializer, SKUSerializer


@method_decorator(merge_cookie_redis,name='post')
class RegisterView(CreateAPIView):
    """
    注册逻辑 post 请求
    """
    serializer_class = CreateUserSerializer
    # 1.获取参数 获取请求体传递过来的参数
    # 2.校验参数  引入序列化器
    # 3.创建一个新的数据模型
    # 4.返回这个模型对象


# 判断用户是都已近存在 GET usernames/(?P<username>\w{5,20})/count/
class UsernameCountView(APIView):
    def get(self, request, username):
        count = User.objects.filter(username=username).count()
        data = {
            'username': username,
            'count': count
        }
        return Response(data)


# 判断手机号是否已经存在  GET mobiles/(?P<mobile>1[3-9]\d{9})/count
class MobileCountView(APIView):
    def get(self, request, mobile):
        count = User.objects.filter(mobile=mobile).count()
        data = {
            'mobile': mobile,
            'count': count
        }
        return Response(data)


class UserDetailView(RetrieveAPIView):
    # 1.获取一个用户信息
    serializer_class = UserDetailSerializer
    permission_classes = [IsAuthenticated]

    def get_object(self):
        return self.request.user


class EmailView(UpdateAPIView):
    serializer_class = EmailSerializer
    permission_classes = [IsAuthenticated]

    def get_object(self):
        return self.request.user


class VerifyEmailView(APIView):
    # 请求方式：GET /emails/verification/?token=xxx
    # 校验发给邮箱绑定的链接里面携带的token值
    # 取出参数
    def get(self, request):
        token = request.query_params.get('token', None)
        if not token:
            return Response({
                'message': '链接无效'
            }, status=status.HTTP_400_BAD_REQUEST)
        # data = {'user_id': self.id, 'email': self.email}
        data = User.verify_token(token)
        try:
            user = User.objects.get(id=data['user_id'], email=data['email'])
        except User.DoesNotExist:
            return Response({
                'message': '链接失效'
            }, status=status.HTTP_400_BAD_REQUEST)
        else:
            user.email_active = True
            user.save()
            return Response({
                'message': 'OK'
            })


class AddressViewSet(mixins.CreateModelMixin, mixins.UpdateModelMixin, GenericViewSet):
    """
    用户地址新增与修改
    """
    serializer_class = UserAddressSerializer
    permissions = [IsAuthenticated]

    def get_queryset(self):
        return self.request.user.addresses.filter(is_deleted=False)

    def list(self, request, *args, **kwargs):
        """
        用户地址列表数据
        """
        queryset = self.get_queryset()
        serializer = self.get_serializer(queryset, many=True)
        user = self.request.user
        return Response({
            'user_id': user.id,
            'default_address_id': user.default_address_id,
            'limit': 20,
            'addresses': serializer.data,
        })

    def create(self, request, *args, **kwargs):
        """
        保存用户地址数据
        """
        # 检查用户地址数据数目不能超过上限
        count = request.user.addresses.count()
        if count >= 20:
            return Response({'message': '保存地址数据已达到上限'}, status=status.HTTP_400_BAD_REQUEST)

        return super().create(request, *args, **kwargs)

    def destroy(self, request, *args, **kwargs):
        """
        处理删除
        """
        address = self.get_object()

        # 进行逻辑删除
        address.is_deleted = True
        address.save()

        return Response(status=status.HTTP_204_NO_CONTENT)

    @action(methods=['put'], detail=True)
    def status(self, request, pk=None, address_id=None):
        """
        设置默认地址
        """
        address = self.get_object()
        request.user.default_address = address
        request.user.save()
        return Response({'message': 'OK'}, status=status.HTTP_200_OK)

    @action(methods=['put'], detail=True)
    def title(self, request, pk=None, address_id=None):
        """
        修改标题
        """
        address = self.get_object()
        serializer = AddressTitleSerializer(instance=address, data=request.data)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response(serializer.data)


# 每当点击浏览一次商品就会获得一个sku_id
class UserBrowsingHistoryView(CreateAPIView):
    serializer_class = AddUserBrowsingHistorySerializer
    permission_classes = [IsAuthenticated]

    def get(self, request):
        user_id = request.user.id
        redis_conn = get_redis_connection('history')

        sku_id_list = redis_conn.lrange('history_%s' % user_id, 0, 4)
        sku_list = []
        for sku_id in sku_id_list:
            sku = SKU.objects.get(id=sku_id)
            sku_list.append(sku)

        s = SKUSerializer(sku_list, many=True)

        return Response(s.data)


@method_decorator(merge_cookie_redis,name='post')
class MyObtainJSONWebToken(ObtainJSONWebToken):
    def post(self, request, *args, **kwargs):
        response = super().post(request, *args, **kwargs)

        # 如果用户登录成功，合并购物车
        serializer = self.get_serializer(data=request.data)
        if serializer.is_valid():
            user = serializer.validated_data['user']
            request.user = user
        return response



